#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <pthread.h>
using namespace std;

// 用锁解决，数据不一致问题（pthread锁）
int ticket = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // 定义并初始化锁

void *route(void *args)
{
    string name = static_cast<char *>(args);
    while (true)
    {
        // 对临界区上锁
        pthread_mutex_lock(&lock);
        if (ticket > 0)
        {
            usleep(1000);
            cout << name << ":sells ticket:" << ticket << endl;
            ticket--;
            // 结束访问临界区，解锁
            pthread_mutex_unlock(&lock);
        }
        else
        {
            // 结束访问临界区，解锁
            pthread_mutex_unlock(&lock);
            break;
        }
    }

    return nullptr;
}

int main()
{
    pthread_t t1, t2, t3, t4;

    pthread_create(&t1, NULL, route, (void *)"thread 1");
    pthread_create(&t2, NULL, route, (void *)"thread 2");
    pthread_create(&t3, NULL, route, (void *)"thread 3");
    pthread_create(&t4, NULL, route, (void *)"thread 4");
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);
}

// 演示数据不一致问题：抢票
//  int ticket = 1000;

// void *route(void *args)
// {
//     string name = static_cast<char *>(args);
//     while (true)
//     {
//         if (ticket > 0)
//         {
//             usleep(1000);
//             cout << name << ":sells ticket:" << ticket << endl;
//             ticket--;
//         }
//         else
//             break;
//     }

//     return nullptr;
// }

// int main()
// {
//     pthread_t t1, t2, t3, t4;

//     pthread_create(&t1, NULL, route, (void *)"thread 1");
//     pthread_create(&t2, NULL, route, (void *)"thread 2");
//     pthread_create(&t3, NULL, route, (void *)"thread 3");
//     pthread_create(&t4, NULL, route, (void *)"thread 4");
//     pthread_join(t1, NULL);
//     pthread_join(t2, NULL);
//     pthread_join(t3, NULL);
//     pthread_join(t4, NULL);
// }